package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    /**
     * 自媒体用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmLoginDto dto) {
       //健壮性判断
        //存不存在
        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String dtoPwd = dto.getPassword();
        String wmPwd = wmUser.getPassword();
        boolean flag = BCrypt.checkpw(dtoPwd, wmPwd);
        //验证密码
        if (!flag){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //验证状态
        if (wmUser.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.INVALID_STATUS);
        }
        //生成token
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        Map hashMap = new HashMap();
        hashMap.put("token",token);
        hashMap.put("user",wmUser);

        return ResponseResult.okResult(hashMap);
    }
}